package springsecurityrabclogin.service.impl;

import jakarta.annotation.Resource;
import springsecurityrabclogin.entity.TPermission;
import springsecurityrabclogin.entity.TUser;
import springsecurityrabclogin.mapper.TPermissionMapper;
import springsecurityrabclogin.mapper.TRoleMapper;
import springsecurityrabclogin.mapper.TUserMapper;
import springsecurityrabclogin.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private TRoleMapper tRoleMapper;
    @Resource
    private TPermissionMapper tPermissionMapper;

    //逆向工程、反向工程（根据数据库表，生成mapper接口、mapper.xml、实体类）
    /**
     * 该方法会在spring security框架登录的时候被调用
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据提交的username 查询数据库是否存在用户
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if(tUser == null){
            throw new UsernameNotFoundException("登录账号不存在");
        }

//        //查询该用户的角色列表（一个用户可能有多个角色）
//        List<TRole> tRoleList = tRoleMapper.selectByUserId(tUser.getId());
//        //把查询出来的角色放入用户对象中
//        tUser.setTRoleList(tRoleList);

        //查询该用户的权限code列表（一个用户可能有多个权限code）
        List<TPermission> tPermissionList = tPermissionMapper.selectByUserId(tUser.getId());
        //把查询出来的权限code放入用户对象中
        tUser.setTPermissionList(tPermissionList);

        //返回该用户对象
        return tUser;
    }
}
